//
//  ZQQAudioDownLoader.m
//  播放器
//
//  Created by MoDao-iOS on 2017/7/19.
//  Copyright © 2017年 MoDao-iOS. All rights reserved.
// 只负责下载某一个区间的数据

/** 只负责下载某一个区间的数据 */

#import "ZQQAudioDownLoader.h"
#import "ZQQRemoteAudioFile.h"

@interface ZQQAudioDownLoader ()<NSURLSessionDataDelegate>

@property (nonatomic, strong) NSURLSession *session;

@property (nonatomic, strong) NSOutputStream *outputStream;

@property (nonatomic, strong) NSURL *url;

@end

@implementation ZQQAudioDownLoader

- (NSURLSession *)session {
    if (!_session) {
        _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    }
    return _session;
}

- (void)downLoadWithURL:(NSURL *)url offset:(long long)offset{
    self.url = url;
    self.offset = offset;
    
    // 下载之前先清空之前的下载任务与临时缓存
    [self cancelAndClean];

    // 请求的是某一个区间的 Range
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:0];
    [request setValue:[NSString stringWithFormat:@"bytes=%lld-", offset] forHTTPHeaderField:@"Range"];
    
    NSURLSessionTask *task = [self.session dataTaskWithRequest:request];
    [task resume];
}

- (void)cancelAndClean {
    // 取消
    [self.session invalidateAndCancel];
    self.session = nil;
    // 清空本地已经存储的临时缓存
    [ZQQRemoteAudioFile clearTmpFile:self.url];
    // 重置数据
    self.loadedSize = 0;
}

#pragma mark - NSURLSessionDataDelegate  

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSHTTPURLResponse *)response
 completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
    
    self.totalSize = [response.allHeaderFields[@"Content-Length"] longLongValue];
    NSString *contentRangeStr = response.allHeaderFields[@"Content-Range"];
    if (contentRangeStr.length != 0) {
        self.totalSize = [[contentRangeStr componentsSeparatedByString:@"/"].lastObject longLongValue];
    }
    self.mimeType = response.MIMEType;
    
    // 开启输出流
    self.outputStream = [NSOutputStream outputStreamToFileAtPath:[ZQQRemoteAudioFile tmpFilePath:self.url] append:YES];
    [self.outputStream open];
    
    completionHandler(NSURLSessionResponseAllow);
}

- (void)URLSession:(NSURLSession *)session dataTask:(nonnull NSURLSessionDataTask *)dataTask didReceiveData:(nonnull NSData *)data {
    self.loadedSize += data.length;
    [self.outputStream write:data.bytes maxLength:data.length];
    
    if ([self.delegate respondsToSelector:@selector(downLoading)]) {
        [self.delegate downLoading];
    }
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(nullable NSError *)error {
    if (error == nil) {
        if ([ZQQRemoteAudioFile tmpFileSize:self.url] == self.totalSize) {
            [ZQQRemoteAudioFile moveTmpPathToCachePath:self.url];
        }
    } else {
        NSLog(@"下载有无");
    }
}
@end
